package com.cet.algorithm.哈希表;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @program: algorithm
 * @description: 两数组交集2.0
 * @author: 陈恩涛
 * @create: 2022-03-15 10:23
 **/
public class LC350 {
    public static int[] intersect(int[] nums1, int[] nums2) {
        List<Integer> list = new ArrayList<>();
        Counter counter = new Counter();
        int length1 = nums1.length;
        int length2 = nums2.length;
        for (int i = 0; i < length2; i++) {
            counter.add(nums2[i]);
        }
        for (int i = 0; i < length1; i++) {
            if (counter.get(nums1[i]) > 0) {
                list.add(nums1[i]);
                counter.decrease(nums1[i]);
            }
        }
        int i = 0;
        int[] result = new int[list.size()];
        for (Integer item : list) {
            result[i++] = item;
        }
        return result;

    }

    public static void main(String[] args) {

    }
}

class Counter extends HashMap<Integer, Integer> {
    public int get(int k) {
        return containsKey(k) ? super.get(k) : 0;
    }

    public void add(int k) {
        put(k, get(k) + 1);
    }

    public void decrease(int k) {
        if (get(k) > 0) {
            put(k, get(k) - 1);
        } else {
            remove(k);
        }
    }
}
